package example;

import org.junit.Before;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SortTest {
    
    Map<String, Date> map = new HashMap<>();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @Before
    public void mock() throws Exception {
        map.put("01", format.parse("2019-06-10"));
        map.put("02", format.parse("2019-06-09"));
        map.put("03", format.parse("2019-06-08"));
        map.put("04", format.parse("2019-06-07"));
        map.put("05", format.parse("2019-06-06"));
        map.put("06", format.parse("2019-06-05"));
        map.put("07", format.parse("2019-06-04"));
        map.put("08", format.parse("2019-06-03"));
        map.put("09", format.parse("2019-06-02"));
    }
    
    
    /**
     * 排序 Stream
     */
    @Test
    public void stream() throws Exception {

        Date current = format.parse("2019-06-07");

        LinkedHashMap<String, Date> linkedHashMap = map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue((last, next) ->
                        - (int) ( Math.abs(current.getTime() - last.getTime()) -  Math.abs(current.getTime() - next.getTime()) )
                ))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (o, n) -> n, LinkedHashMap::new));

        linkedHashMap.forEach((key, value) -> System.out.println(key + " : " + value));

    }
    
    
    
    

    /**
     * 排序 Entry
     */
    @Test
    public void entry() throws ParseException {
        Date current = format.parse("2019-06-07");
        
        List<Map.Entry<String, Date>> list = new ArrayList<>(map.entrySet());

        list.sort((o1, o2) -> (int) (Math.abs(current.getTime() - o1.getValue().getTime())
                - Math.abs(current.getTime() - o2.getValue().getTime())));

        list.forEach(System.out::println);
    }
}
